#include <iostream>
#include <pthread.h>
#include <vector>
#include <unistd.h>
#include <semaphore.h>  


template <class T>
class RingQueue
{
    const static int defaultcap = 10;
public:
    RingQueue(int maxcap_ = defaultcap)
    : ringqueue_(maxcap_)
    , maxcap_(maxcap_)
    , c_step_(0)
    , p_step_(0)
    {
        sem_init(&cdata_sem_, 0, 0);
        sem_init(&pspace_sem_, 0, maxcap_);
        pthread_mutex_init(&c_mutex_, nullptr);
        pthread_mutex_init(&p_mutex_, nullptr);
    }

    void P(sem_t& pspace_sem_)
    {
        sem_wait(&pspace_sem_);
    }

    void V(sem_t& cdata_sem_)
    {
        sem_post(&cdata_sem_);
    }

    void Lock(pthread_mutex_t& mutex)
    {
        pthread_mutex_lock(&mutex);
    }

    void Unlock(pthread_mutex_t& mutex)
    {
        pthread_mutex_unlock(&mutex);
    }

    void Push(const T& in)
    {
        P(pspace_sem_);
        Lock(p_mutex_);
        ringqueue_[p_step_] = in;
        p_step_ = (p_step_ + 1) % maxcap_;
        Unlock(p_mutex_);
        V(cdata_sem_);
    }

    T Pop()
    {
        P(cdata_sem_);
        Lock(c_mutex_);
        T out = ringqueue_[c_step_];
        c_step_ = (c_step_ + 1) % maxcap_;
        Unlock(c_mutex_);
        V(pspace_sem_);
        return out;
    }

    ~RingQueue()
    {
        sem_destroy(&cdata_sem_);
        sem_destroy(&pspace_sem_);
        pthread_mutex_destroy(&c_mutex_);
        pthread_mutex_destroy(&p_mutex_);
    }
private:
    std::vector<T> ringqueue_;
    int maxcap_;

    int c_step_;
    int p_step_;

    sem_t cdata_sem_;
    sem_t pspace_sem_;

    pthread_mutex_t c_mutex_;
    pthread_mutex_t p_mutex_;
};